package e.odbo.data.util;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
    private static final char [] hexchars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    private static final NumberFormat cardformat = new DecimalFormat("000000");
    private static final Random cardrandom = new Random();

    /** Creates a new instance of StringUtils */
    private StringUtils() {
    }

    public static String getCardNumber() {
        return cardformat.format(Math.abs(System.currentTimeMillis()) % 1000000L)
                + cardformat.format(Math.abs(cardrandom.nextLong()) % 1000000L);
    }

    public static String encodeXML(String sValue) {

        if (sValue == null) {
            return null;
        } else {
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < sValue.length(); i++) {
                char charToCompare = sValue.charAt(i);
                if (charToCompare == '&') {
                    buffer.append("&amp;");
                } else if (charToCompare == '<') {
                    buffer.append("&lt;");
                } else if (charToCompare == '>') {
                    buffer.append("&gt;");
                } else if (charToCompare == '\"') {
                    buffer.append("&quot;");
                } else if (charToCompare == '\'') {
                    buffer.append("&apos;");
                } else {
                    buffer.append(charToCompare);
                }
            }
            return buffer.toString();
        }
    }

    public static String byte2hex(byte[] binput) {

        StringBuffer sb = new StringBuffer(binput.length * 2);
        for (int i = 0; i < binput.length; i++) {
            int high = ((binput[i] & 0xF0) >> 4);
            int low = (binput[i] & 0x0F);
            sb.append(hexchars[high]);
            sb.append(hexchars[low]);
        }
        return sb.toString();
    }

    public static byte [] hex2byte(String sinput) {
        int length = sinput.length();

        if ((length & 0x01) != 0) {
            throw new IllegalArgumentException("odd number of characters.");
        }

        byte[] out = new byte[length >> 1];

        // two characters form the hex columnName.
        for (int i = 0, j = 0; j < length; i++) {
            int f = Character.digit(sinput.charAt(j++), 16) << 4;
            f = f | Character.digit(sinput.charAt(j++), 16);
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    public static String readResource(String resource) throws IOException {

        InputStream in = StringUtils.class.getResourceAsStream(resource);
        if (in == null) {
            throw new FileNotFoundException(resource);
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        byte[] data = out.toByteArray();

        return new String(data, "UTF-8");
    }

    public static boolean isNumber(String sCardNumber){

        if ( (sCardNumber==null) || (sCardNumber.equals("")) ){
            return false;
        }

        for (int i = 0; i < sCardNumber.length(); i++) {
            char c = sCardNumber.charAt(i);
            if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
                return false;
            }
        }

        return true;
    }

    public static ArrayList<String> splitProp(String prop){
        return splitProp(prop,",");
    }

    public static ArrayList<String> splitProp(String prop,String splitChr){
        ArrayList<String> propList=new ArrayList<String>();
        if(prop==null||prop.isEmpty())
            return propList;
        String[] propEntry=prop.split(splitChr);
        for(int i=0;i<propEntry.length;i++)
            propList.add(propEntry[i]);
        return propList;
    }

    public static String stringArrayConcat(String[] arr,String split){
        StringBuffer result = new StringBuffer();
        for(String s:arr){
            result.append(s);
            result.append(split);
        }
        return result.toString();
    }

    public static String join(Object[] array, char separator) {
        if (array == null) {
            return null;
        }
        int arraySize = array.length;
        int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize);
        StringBuffer buf = new StringBuffer(bufSize);

        for (int i = 0; i < arraySize; i++) {
            if (i > 0) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }

    public static <T> String join(Iterator<T> iterator, String separator) {
        // handle null, zero and one elements before building a buffer

        if (iterator == null) {
            return null;
        }

        if (!iterator.hasNext()) {
            return "";
        }

        T first = iterator.next();
        if (!iterator.hasNext()) {
            return String.valueOf(first);
        }
        // two or more elements
        StringBuffer buf = new StringBuffer(256); // Java sample is 16, probably too small
        if (first != null) {
            buf.append(first);
        }
        while (iterator.hasNext()) {
            if (separator != null) {
                buf.append(separator);
            }
            Object obj = iterator.next();
            if (obj != null) {
                buf.append(obj);
            }
        }
        return buf.toString();
    }

    public static final char UNDERLINE = '_';

    /**
     * 驼峰格式字符串转换为下划线格式字符串
     *
     * @param param
     * @return
     */
    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串
     *
     * @param param
     * @return
     */
    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == UNDERLINE) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串2
     *
     * @param param
     * @return
     */
    public static String underlineToCamelUsePattern(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        StringBuilder sb = new StringBuilder(param);
        Matcher mc = Pattern.compile("_").matcher(param);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }

    public static String upStartChar(String nameStr,boolean up){
        Character firstChar=nameStr.charAt(0);
        if(up)
            nameStr=String.valueOf(firstChar).toUpperCase()+nameStr.substring(1);
        else
            nameStr=String.valueOf(firstChar).toLowerCase()+nameStr.substring(1);
        return nameStr;
    }

    public static String fill(String start,String end,int length,char fillChar){
        if(null==start)
            start="";
        if(null==end)
            end="";
        int fillLength=length-start.length()-end.length();
        if(fillLength<=0)
            return start+end;
        StringBuilder ret=new StringBuilder(start);
        while (fillLength-->0)
            ret.append(fillChar);
        return ret.append(end).toString();
    }
}
